
<template>
  <div id="app">
    <div class="show-box">
      <img :src="imgSrc" alt />
    </div>
    <form class="input-box">
      <div class="select">
        选择文件
        <input type="file" name="upphoto" @change="input" />
        <!--后端读取的是name为upphoto的标签-->
      </div>
      <div class="button" @click="loadImg">点击上传</div>
    </form>
  </div>
</template>

<script>
import $ from 'jquery'

export default {
  name: 'app',
  data () {
    return {
      maxSize: 500, // 限制图片最大为500kb
      file: '',
      imgSrc: '',
      formData: ''
    }
  },
  methods: {
    readFileImg (file) {
      // 读取图片信息并展示
      const reader = new FileReader() // 读取文件实例
      reader.readAsDataURL(file) // 将文件读取为 DataURL
      reader.onload = () => { // 文件读取成功完成时触发
        const img = new Image()
        img.src = reader.result // 文件一旦开始读取，无论成功或失败，实例的 result 属性都会被填充。如果读取失败，则 result 的值为 null ，否则即是读取的结果，绝大多数的程序都会在成功读取文件的时候，抓取这个值。
        img.onload = () => {
          this.imgSrc = img.src // 以上是将选择的图片展示出来
          const originWidth = img.naturalWidth // 获取图片原始大小
          const originHeight = img.naturalHeight
          const originSize = file.size / 1024 // 计算图片多少kb
          this.compressEvent(img, originSize, originWidth, originHeight)
        }
      }
      reader.onerror = function (error) {
        console.log(`error: ${error}`)
      }
    },
    compressEvent (img, originSize, originWidth, originHeight) {
      // 将图片绘制到canvas上进行压缩
      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')
      const maxSize = this.maxSize
      if (originSize <= maxSize) {
        this.formData = new FormData($('.input-box')[0])
        return false
      }
      const mul = originSize / maxSize
      const targetWidth = originWidth / mul
      const targetHeight = originHeight / mul
      canvas.width = targetWidth
      canvas.height = targetHeight
      context.clearRect(0, 0, targetWidth, targetHeight) // 清除画布
      context.drawImage(img, 0, 0, targetWidth, targetHeight) // 画图

      const dataURL = canvas.toDataURL('image/jpeg', 0.1) // 将其转化成base64字符串

      const blob = this.dataURItoBlob(dataURL) // 转化为blob格式

      this.formData = new FormData()
      this.formData.append('file', blob, this.file.name)
    },
    dataURItoBlob (dataURI) {
      // base64格式转化为blob对象
      const byteString = atob(dataURI.split(',')[1])

      const mimeString = dataURI
        .split(',')[0]
        .split(':')[1]
        .split(';')[0]

      const ab = new ArrayBuffer(byteString.length)
      const ia = new Uint8Array(ab)
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
      }

      return new Blob([ab], { type: mimeString })
    },
    input (event) {
      // 选择文件
      this.readFileImg(event.target.files[0])
    },
    loadImg () {
      // 点击上传
      $.ajax({
        url: './downFile.php', // 接口地址
        type: 'POST',
        async: false,
        data: this.formData,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
          this.imgSrc = ''
        },
        error: function (error) {
          console.log(error)
        }
      })
    }
  }
}
</script>
